package com.itheima.rpc.server.registry.zk;

import com.itheima.rpc.annotation.HrpcService;
import com.itheima.rpc.server.config.RpcServerConfiguration;
import com.itheima.rpc.server.registry.RpcRegistry;
import com.itheima.rpc.spring.SpringBeanFactory;
import com.itheima.rpc.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @desc 基于zookeeper实现服务注册
 * @author:ivan.liu
 */
@Component
@Slf4j
public class ZkRpcRegistry implements RpcRegistry {

    //zookeeper客户端操作类
    @Autowired
    private ServerZKit zKit;
    //配置文件读取类
    @Autowired
    private RpcServerConfiguration configuration;

    @Autowired
    private SpringBeanFactory beanFactory;

    @Override
    public void registry() {
        //获取类上有@HrpcService注解的类
        Map<String, Object> objectMap = SpringBeanFactory.getBeanListByAnnotationClass(HrpcService.class);
        if(objectMap!=null&&!objectMap.isEmpty()){
            //创建根目录
            zKit.createRootNode();
            //获取本机ip
            String ip = IpUtil.getRealIp();
            //Map的Value存储具体的Bean对象
            for (Object bean : objectMap.values()) {
                //根据@HrpcService注解获取注册的类的信息
                HrpcService hrpcService = bean.getClass().getAnnotation(HrpcService.class);
                String className = hrpcService.interfaceClass().getName();
                //创建节点目录，采用持久化节点
                zKit.createPersistentNode(className);
                //从配置文件中获取Rpc的端口
                int port = configuration.getRpcPort();
                //注册ip和端口到zk，采用临时节点，便于通知服务消费方
                zKit.createNode(className+"/"+ip+":"+port);
                log.info("服务注册成功，注册服务名：{}，注册ip:port：{}",className,ip+":"+port);
            }
        }
    }
}
